package com.itcast.mobileController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itcast.health.constant.MessageConstant;
import com.itcast.health.constant.RedisMessageConstant;
import com.itcast.health.pojo.Member;
import com.itcast.health.pojo.Result;
import com.itcast.health.utils.JedisUtil;
import com.itcast.service.LoginMobileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * @author Wang
 * @version v1.0
 * @date 2019/12/1 9:41
 * @description 登录
 **/
@RestController
@RequestMapping("login")
public class LoginMobileController {
    @Reference
    LoginMobileService loginMobileService;
    @Autowired
    JedisUtil jedisUtil;

    @RequestMapping("check")
    public Result check(HttpServletRequest request, HttpServletResponse response, @RequestBody Map map) {
        //用户提交的手机号
        String telephone = (String) map.get("telephone");
        //用户输入的验证码
        String validateCode = (String) map.get("validateCode");
        //将用户输入的验证码与redis中的进行比对
        String code = jedisUtil.get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        if (code == null || !code.equals(validateCode)) {
            //用户验证码输入错误
            return Result.error(MessageConstant.VALIDATECODE_ERROR);
        }
        //验证码输入正确,查看该号码是否为会员
        Member member = loginMobileService.findByTelephone(telephone);
        if (member == null) {
            //该号码不是会员,自动注册
            member = new Member();//初始化对象
            member.setRegTime(new Date());//注册时间
            member.setPhoneNumber(telephone);//注册的手机号
            loginMobileService.add(member);
        }


        //把用户信息保存在redis

        String token = UUID.randomUUID().toString();
        jedisUtil.setex(token,60 *60* 120, JSON.toJSONString(member));
        //返回token浏览器或者app自己存储，下次请求带上
        return Result.success("",token);

    }
}